import asyncio, tempfile, traceback, os


def extract_pdf_text(pdf_path: str):
    text = ""
    # with pdfplumber.open(pdf_path) as pdf:
    #     for page in pdf.pages:
    #         text += page.extract_text() or ""
    return text
def is_file_in_temp(file_path):
    """判断文件是否位于系统临时目录下"""
    # 获取系统临时目录
    temp_dir = tempfile.gettempdir()
    # 规范化路径，处理大小写和斜杠差异
    temp_dir: str = os.path.normcase(os.path.abspath(temp_dir))
    file_path: str = os.path.normcase(os.path.abspath(file_path))
    # 检查文件路径是否以临时目录路径开头
    return file_path.startswith(temp_dir)

def catch_callback(err: Exception) :
    # print(err)
    print(traceback.format_exc())
    # logger.error(traceback.format_exc())
    
async def async_catch_callback(err: Exception) :
    # print(err)
    print(traceback.format_exc())
    # logger.error(traceback.format_exc())

def catchable(callback: callable = None) :
    if callback is None :
        callback = catch_callback
    def decorator(func):
        def catchable_wrapper(*args, **kwargs):
            try :
                # logger.debug('start catchable')
                result = func(*args, **kwargs)
                # logger.debug('finish catchable')
                return result
            except Exception as err:
                # logger.debug('catchable callback')
                return callback(err)
        return catchable_wrapper
    return decorator

def async_catchable(callback: callable = None) :
    if callback is None :
        callback = async_catch_callback
    def decorator(func):
        async def async_catchable_wrapper(*args, **kwargs):
            try :
                # logger.debug('start catchable')
                if asyncio.iscoroutinefunction(func) :
                    result = await func(*args, **kwargs)
                else :
                    result = func(*args, **kwargs)
                # logger.debug('finish catchable')
                return result
            except Exception as err:
                # logger.debug('catchable callback')
                if asyncio.iscoroutinefunction(callback) :
                    return await callback(err)
                else :
                    return callback(err)
        return async_catchable_wrapper
    return decorator